import { app, BrowserWindow, ipcMain, dialog } from 'electron'
import { join } from 'path'
import path from 'path'
import { electronApp, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import WsServer from './websocket/Server'
import log from 'electron-log'
import fs from 'fs'
// import { testFunc } from './native'

// WebSocket 服务器
let wsServer: WsServer | null = null

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 730,
    height: 700,
    minHeight: 700,
    // minWidth: 900,
    minWidth:730,
    show: false,
    frame: false,
    autoHideMenuBar: true,
    icon: icon,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 全局变量初始化
  globalThis.mainWindow = mainWindow
  globalThis.autoSend = true

  registerIpcEvents(mainWindow)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()

    // 设置日志文件路径
    log.transports.file.resolvePathFn = () => path.join(app.getPath('userData'), 'logs', 'app.log')
  })

  // mainWindow.webContents.setWindowOpenHandler((details) => {
  //   shell.openExternal(details.url)
  //   return { action: 'deny' }
  // })

  // 禁用F12和Ctrl+Shift+I
  mainWindow.webContents.on('before-input-event', (event, input) => {
    if (input.key === 'F12' || (input.key === 'i' && input.control && input.shift)) {
      event.preventDefault()
    }
  })

  mainWindow.setMenu(null)

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // testFunc(mainWindow)
}

app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('kikolove-test-tool')
  // app.on('browser-window-created', (_, window) => {
  //   optimizer.watchWindowShortcuts(window)
  // })

  createWindow()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  globalThis.exit = true
  if (process.platform !== 'darwin') {
    wsServer?.closeAll()
    ipcMain.removeAllListeners()
    app.quit()
  }
})

/**
 * 注册IPC事件
 */
const registerIpcEvents = (mainWindow: BrowserWindow) => {
  // 打开devtools
  ipcMain.on('open-devtools', () => {
    mainWindow.webContents.openDevTools()
  })

  // 最小化窗口
  ipcMain.on('minimize-window', () => {
    mainWindow.minimize()
  })

  // 最大化窗口
  ipcMain.on('maximize-window', () => {
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize()
    } else {
      mainWindow.maximize()
    }
  })

  // 关闭窗口
  ipcMain.on('close-window', () => {
    mainWindow.close()
  })

  // 打开文件选择对话框
  ipcMain.handle('open-file-dialog', async () => {
    log.info('open-file-dialog')
    const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
      properties: ['openFile'],
      filters: [
        { name: 'JSON Files', extensions: ['json'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    })
    if (!canceled && filePaths.length > 0) {
      return { filePaths }
    }
    return { filePaths: [] }
  })

  // 创建WebSocket服务器
  ipcMain.handle('start-server', (_, platform: string, wssport: number) => {
    globalThis.targetPlatform = platform
    log.info('对应测试平台：', globalThis.targetPlatform)

    if (wsServer) {
      const addr = wsServer?.wss?.address()
      return typeof addr === 'string' ? 0 : (addr?.port ?? 0)
    }
    wsServer = new WsServer(wssport)
    const addr = wsServer?.wss?.address()
    const port = typeof addr === 'string' ? 0 : (addr?.port ?? 0)
    return port
  })

  // 关闭WebSocket服务器
  ipcMain.handle('stop-server', () => {
    wsServer?.closeAll()
    wsServer?.close()
    wsServer = null
    log.info('WebSocket服务器已关闭')
    return true
  })

  // 读取文件
  ipcMain.handle('read-file', async (_, filePath: string) => {
    try {
      const fileContent = await fs.promises.readFile(filePath, 'utf8')
      globalThis.mainWindow.webContents.send('render-log', {
        type: 'read-file',
        message: `读取文件成功：${filePath}`,
        tagType: 'system',
      })
      const data = JSON.parse(fileContent)
      globalThis.fileData = data

      // 添加文件监听
      if (globalThis.fileWatcher) {
        globalThis.fileWatcher.close()
      }

      // 定义数据类型检测函数
      const detectDataTypes = (data: any[]): string[] => {
        const typeMap = {
          currentCsr: false,
          currentConv: false,
          remote_his_message: false,
          message: false,
          newMsg: false
        }

        // 单次遍历检测所有类型
        for (const item of data) {
          const type = item?.content?.type
          if (type in typeMap) {
            typeMap[type] = true
            // 如果所有类型都已找到，提前退出循环
            if (Object.values(typeMap).every(Boolean)) break
          }
        }

        return Object.entries(typeMap)
          .filter(([_, exists]) => exists)
          .map(([type]) => type)
      }

      // 添加防抖计时器
      let debounceTimer: NodeJS.Timeout | null = null
      globalThis.fileWatcher = fs.watch(filePath, async (eventType) => {
        if (eventType === 'change') {
          // 清除之前的计时器
          if (debounceTimer) {
            clearTimeout(debounceTimer)
          }

          // 设置新的计时器
          debounceTimer = setTimeout(async () => {
            try {
              const newContent = await fs.promises.readFile(filePath, 'utf8')
              const newData = JSON.parse(newContent)
              globalThis.fileData = newData

              const newDataTypes = detectDataTypes(newData)
              globalThis.mainWindow.webContents.send('render-log', {
                type: 'file-changed',
                message: `文件已更新：${filePath}`,
                dataTypes: newDataTypes
              })
              // 发送新的数据类型给渲染进程
              globalThis.mainWindow.webContents.send('render-data-types', newDataTypes)
            } catch (error) {
              log.error('文件更新时读取出错:', error)
            }
          }, 200) // 200ms的防抖时间
        }
      })

      const dataTypes = detectDataTypes(data)
      globalThis.mainWindow.webContents.send('render-data-types', dataTypes)
      return { data, dataTypes }
    } catch (error) {
      log.error('读取文件时出错:', error)
      return null
    }
  })

  // 清除文件内容
  ipcMain.handle('clear-file', () => {
    if (globalThis.fileWatcher) {
      globalThis.fileWatcher.close()
      globalThis.fileWatcher = null
    }
    globalThis.fileData = null
    globalThis.mainWindow.webContents.send('render-data-types', [])
    log.info('已清除文件内容')
    return true
  })

  // 关闭客户端连接
  ipcMain.on('close-client', () => {
    wsServer?.closeAll()
  })

  // 模拟发送消息
  ipcMain.on('send-data', async (_, messageType: string = 'message') => {
    try {
      if (!wsServer?.checkWs()) {
        globalThis.mainWindow.webContents.send('render-log', {
          type: 'no-ws',
          message: `暂无客户端连接`,
          tagType: 'error'
        })
        log.error('WebSocket服务器未连接')
        return
      }

      const MESSAGE_INTERVAL = 500 // 消息间隔时间（毫秒）
      const messageData =
        globalThis.fileData?.filter((item: any) => item?.content?.type === messageType) || []

      messageData.forEach((item: any, index: number) => {
        setTimeout(() => {
          try {
            wsServer?.sendMessage(item)
            log.info(`成功发送第${index + 1}条${messageType}消息`)
          } catch (error) {
            log.error(`发送第${index + 1}条${messageType}消息时出错:`, error)
          }
        }, index * MESSAGE_INTERVAL)
      })

      log.info(`${messageType}消息发送完成`)
    } catch (error) {
      log.error(`处理${messageType}数据文件时出错:`, error)
    }
  })

  // 全局标记是否自动发送基础信息
  ipcMain.on('sign-auto-send', (_, flag: boolean) => {
    globalThis.autoSend = flag ?? false
  })
}
